import 'dart:convert';

import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'package:juming_test/config/app_router_path.dart';
import 'package:juming_test/routes/app_router.dart';
import 'package:juming_test/view_models/domain/domain_filter_view_model.dart';

class DomainFilterLogic extends GetxController {
  // 页面传参
  String paramsData = '';
  // 域名筛选ViewModel
  final DomainFilterViewModel domainFilterViewModel = Get.put(
    DomainFilterViewModel(),
    tag: 'DomainFilter',
  );

  // 选中的 index
  final Rx<int> selectedIndex = Rx(0);

  @override
  void onReady() {
    super.onReady();
    _initParamsData();
  }

  @override
  void onClose() {
    super.onClose();
    Get.delete<DomainFilterViewModel>(tag: 'DomainFilter');
  }

  // 初始化页面传参
  void _initParamsData() {
    if (paramsData.isEmpty) {
      return;
    }
    domainFilterViewModel.onReady().then((_) {
      domainFilterViewModel.updateByData(jsonDecode(paramsData));
    });
  }

  // 更新选中的 index
  void updateSelectedIndex(int index) {
    selectedIndex.value = index;
  }

  // 确认筛选
  void confirmFilter() {
    final appRouter = GetIt.I<AppRouter>();
    final previousPage =
        appRouter.stack.length > 1
            ? appRouter.stack[appRouter.stack.length - 2]
            : null;
    String dataStr = domainFilterViewModel.getParamsDataString();
    if (previousPage?.routeData.path == AppRouterPath.domainList) {
      appRouter.pop(dataStr);
    } else {
      appRouter.replacePath('${AppRouterPath.domainList}?data=$dataStr');
    }
  }
}
